package com.czl.module_storehouse.activity.inventory.select;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.czl.base.config.AppConstants;
import com.czl.base.data.bean.tengyun.LocatListBean;
import com.czl.base.data.bean.tengyun.SortBean;
import com.czl.module_base.bean.ListBean;
import com.czl.module_base.http.HttpResponse;
import com.czl.module_base.mvp.presenter.InjectPresenter;
import com.czl.module_base.utils.PopWindowUtils;
import com.czl.module_storehouse.R;
import com.czl.module_storehouse.activity.base.BaseOperationLocationActivity;
import com.czl.module_storehouse.activity.inventory.scan.InventoryScanActivity;
import com.czl.module_storehouse.adapter.InventoryLocationAdapter;
import com.czl.module_storehouse.adapter.InventoryRoomAdapter;
import com.czl.module_storehouse.adapter.InventorySelectAdapter;
import com.czl.module_storehouse.adapter.tree.ListTree;
import com.czl.module_storehouse.adapter.tree.ListTreeAdapter;
import com.czl.module_storehouse.bean.EditInventoryInfoBean;
import com.czl.module_storehouse.bean.InventoryBean;
import com.czl.module_storehouse.bean.RoomListBean;
import com.czl.module_storehouse.databinding.ActivityInventorySelectBinding;
import com.czl.module_storehouse.event.DetailsPostSuccessEvent;
import com.czl.module_storehouse.event.InventoryEvent;
import com.czl.module_storehouse.event.InventoryScanEvent;
import com.czl.module_storehouse.event.InventoryUpdateEvent;
import com.czl.module_storehouse.event.SortEvent;
import com.czl.module_storehouse.listener.OnExpandableItemListener;
import com.czl.module_storehouse.mvp.presenter.InventoryPresenter;
import com.czl.module_storehouse.mvp.presenter.StorehouseLocationPresenter;
import com.czl.module_storehouse.mvp.view.InventoryView;
import com.jeremyliao.liveeventbus.LiveEventBus;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xubin
 */
@Route(path = AppConstants.Router.Service.F_SERVICE_INVENTORY_SELECT)
public class InventorySelectActivity extends BaseOperationLocationActivity<ActivityInventorySelectBinding> implements InventoryView {

    private static final String TAG_DEFAULT_STOREHOUSE_LOCATION = "1";
    /**
     * 仓位信息
     */
    private List<LocatListBean> mStoreHouseBeanList;
    private int mInventoryId;
    private InventorySelectAdapter mAdapter;
    private final EditInventoryInfoBean mEditInventoryInfoBean = new EditInventoryInfoBean();
    private List<RoomListBean> mRoomListBeanList;
    private String mLastSelectedRoomId;
    private String mRoomId;
    private String mLocat;
    private String mLocatId;
    private boolean mSave;
    private int mLastSelectedLocationId;
    @InjectPresenter
    InventoryPresenter mInventoryPresenter;
    @InjectPresenter
    StorehouseLocationPresenter mStorehouseLocationPresenter;

    @Override
    protected ActivityInventorySelectBinding getBinding(LayoutInflater layoutInflater) {
        return ActivityInventorySelectBinding.inflate(layoutInflater);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mToolBinding.toolbarContentTitle.setText("仓库盘点");
        if (getIntent() != null) {
            int inventoryId = getIntent().getIntExtra("inventoryId", 0);
            if (inventoryId > 0) {
                mInventoryId = inventoryId;
            }
        }
        //选择房间
        binding.llLeft.setOnClickListener(v -> showPopupRoom());
        binding.llRight.setOnClickListener(v -> showPopupArea());
        binding.textSave.setOnClickListener(v -> save());
        binding.textComplete.setOnClickListener(v -> submit());
        mAdapter = new InventorySelectAdapter(new ArrayList<>());
        mAdapter.setOnExpandableItemListener(new OnExpandableItemListener<SortBean>() {
            @Override
            public void onGroupItemClick(int groupPosition) {
            }

            @Override
            public void onChildItemClick(View view, int groupPosition, int childPosition, SortBean sortBean) {
                goScanActivity(sortBean);
            }
        });
        binding.expandableListView.setAdapter(mAdapter);
        EventBus.getDefault().register(this);
    }

    private void goScanActivity(SortBean bean) {
        SortEvent event = new SortEvent(bean);
        event.setInventoryId(mInventoryId);
        EventBus.getDefault().postSticky(event);
        startActivity(new Intent(getContext(), InventoryScanActivity.class));
    }

    @Override
    protected void loadData() {
        super.loadData();
        if (mInventoryPresenter != null) {
            mInventoryPresenter.getInventoryRoomInfo(mInventoryId);
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onDataEvent(InventoryEvent event) {
        InventoryBean inventoryBean = event.getInventoryBean();
        if (inventoryBean != null) {
            mInventoryId = inventoryBean.getInventoryId();
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onDataEvent(InventoryScanEvent event) {
        if (event != null) {
            getInventoryData(null, false, false, true);
        }
    }

    private void getInventoryData(EditInventoryInfoBean bean, boolean save, boolean showLoading, boolean showDialogLoading) {
        mSave = save;
        if (mInventoryPresenter != null) {
            mInventoryPresenter.getNeedInventorySortInfo(showLoading, showDialogLoading, mInventoryId, mRoomId, mLocatId, bean);
        }
    }

    @Override
    public <T> void showHttpResponse(HttpResponse<T> httpResponse) {
        super.showHttpResponse(httpResponse);
        String requestTag = httpResponse.getRequestTag();
        if (InventoryPresenter.TAG_INVENTORY_SORT_INFO.equals(requestTag)) {
            ListBean<LocatListBean> listBean = (ListBean<LocatListBean>) httpResponse.getData();
            if (listBean == null) {
                return;
            }
            showLoadSuccess();
            List<LocatListBean> inventorySortInfo = listBean.getList();
            if (mSave) {
                EventBus.getDefault().postSticky(new InventoryUpdateEvent());
                showToast("暂存成功");
            }
            mAdapter.replaceAll(inventorySortInfo, binding.expandableListView, binding.tvInventoryNum);
        } else if (InventoryPresenter.TAG_INVENTORY_ROOM_INFO.equals(requestTag)) {
            ListBean<RoomListBean> listBean = (ListBean<RoomListBean>) httpResponse.getData();
            if (listBean == null) {
                return;
            }
            mRoomListBeanList = listBean.getList();
            if (mRoomListBeanList == null || mRoomListBeanList.isEmpty()) {
                return;
            }
            RoomListBean roomListBean = mRoomListBeanList.get(0);
            setRoomNameByPosition(roomListBean, false);
        } else if (InventoryPresenter.TAG_INVENTORY_EDIT_INFO.equals(httpResponse.getRequestTag())) {
            showToast("盘点成功");
            LiveEventBus.get(DetailsPostSuccessEvent.class).post(new DetailsPostSuccessEvent());
            finish();
        }
    }

    private void setRoomNameByPosition(RoomListBean roomListBean, boolean showDialogLoading) {
        if (roomListBean == null) {
            return;
        }
        binding.textSelectRoom.setText(roomListBean.getRoomName());
        mLocat = roomListBean.getLocat();

        mRoomId = String.valueOf(roomListBean.getRoomId());
        if (mLastSelectedRoomId != null && !mLastSelectedRoomId.equals(mRoomId)) {
            binding.textSelectArea.setText("选择区域");
        }
        mLastSelectedRoomId = mRoomId;
        if (TAG_DEFAULT_STOREHOUSE_LOCATION.equals(mLocat)) {
//                textSelectArea.setEnabled(false);
            mRoomId = null;
            mLocatId = roomListBean.getRoomId();
        } else {
//                textSelectArea.setEnabled(true);
            mRoomId = String.valueOf(roomListBean.getRoomId());
            mStoreHouseBeanList = roomListBean.getChildList();
            binding.textSelectArea.setText("选择区域");
            mLocatId = null;
        }

        getInventoryData(null, false, !showDialogLoading, showDialogLoading);
    }

    private void showPopupArea() {
        if (TextUtils.isEmpty(mRoomId)) {
            showToast("请选择房间");
            return;
        }
        if (TAG_DEFAULT_STOREHOUSE_LOCATION.equals(mLocat)) {
            showToast("默认库位没有区域");
            return;
        }
        if (mStoreHouseBeanList == null || mStoreHouseBeanList.size() == 0) {
            return;
        }
        InventoryLocationAdapter adapter = new InventoryLocationAdapter(new ListTree());
        createPopup(adapter);
        adapter.addAll(mStoreHouseBeanList);
        PopWindowUtils.getInstance().showAsDropDown(binding.llLeft);
        adapter.setOnItemClickListener((ListTreeAdapter.OnItemClickListener<LocatListBean>) (locatListBean, title, pIdPath)
                -> {
            PopWindowUtils.getInstance().dismissPopupWindow();
            callBackModel(locatListBean);
        });
    }

    private void showPopupRoom() {
        if (mRoomListBeanList == null || mRoomListBeanList.size() == 0) {
            return;
        }
        InventoryRoomAdapter adapter = new InventoryRoomAdapter(new ListTree());
        createPopup(adapter);
        adapter.addAll(mRoomListBeanList);
        PopWindowUtils.getInstance().showAsDropDown(binding.llLeft);
        adapter.setOnItemClickListener((ListTreeAdapter.OnItemClickListener<RoomListBean>) (roomListBean, title, pIdPath)
                -> {
            PopWindowUtils.getInstance().dismissPopupWindow();
            setRoomNameByPosition(roomListBean, true);
        });
    }

    private void createPopup(RecyclerView.Adapter<?> adapter) {
        View view = View.inflate(getContext(), R.layout.common_recycler_view, null);
        view.setBackgroundResource(R.drawable.shape_round_white);
        RecyclerView recyclerView = view.findViewById(R.id.rv_item);

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(adapter);
        int width = ScreenUtils.getScreenWidth() - SizeUtils.dp2px(30);
        int height = SizeUtils.dp2px(251);
        PopWindowUtils.getInstance().createPopWindow(getContext(), view, width, height);
    }

    @Override
    protected StorehouseLocationPresenter getLocationPresenter() {
        return mStorehouseLocationPresenter;
    }

    @Override
    protected boolean callBackModel(LocatListBean bean) {
        if (mLastSelectedLocationId == bean.getStorehouseLocatId()) {
            return false;
        } else {
            binding.textSelectArea.setText("选择区域");
        }
        binding.textSelectArea.setText(bean.getStorehouseLocatName());
        mRoomId = bean.getRoomId();
        mLocatId = String.valueOf(bean.getStorehouseLocatId());

        mLastSelectedLocationId = bean.getStorehouseLocatId();
        getInventoryData(null, false, false, true);
        return false;
    }

    private void save() {
        mEditInventoryInfoBean.setInventoryId(mInventoryId);
        mEditInventoryInfoBean.setStatus(2);
        mEditInventoryInfoBean.setLocatList(mAdapter.getData());
        getInventoryData(mEditInventoryInfoBean, true, false, true);
    }

    private void submit() {
        mEditInventoryInfoBean.setInventoryId(mInventoryId);
        mEditInventoryInfoBean.setStatus(1);
        mEditInventoryInfoBean.setLocatList(mAdapter.getData());
        if (mInventoryPresenter != null) {
            mInventoryPresenter.editInventoryInfo(mEditInventoryInfoBean);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            back();
        }
        return super.onKeyDown(keyCode, event);
    }

    protected void back() {
    }
}
